package cn.aitrox.ry.service.anno.service.impl;

import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.enumtype.RespCodeEnum;
import cn.aitrox.ry.service.anno.dao.AnnoComponentResultDao;
import cn.aitrox.ry.service.anno.dao.AnnoLesionResultDao;
import cn.aitrox.ry.service.anno.dao.AnnoLesionResultGroupDao;
import cn.aitrox.ry.service.anno.dao.AnnoResultDao;
import cn.aitrox.ry.service.anno.entity.AnnoLesionResultGroupEntity;
import cn.aitrox.ry.service.anno.entity.AnnoResultEntity;
import cn.aitrox.ry.service.anno.service.AnnoLesionResultGroupService;
import cn.aitrox.ry.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AnnoLesionResultGroupServiceImpl implements AnnoLesionResultGroupService {

    @Autowired
    private AnnoLesionResultGroupDao annoLesionResultGroupDao;

    @Autowired
    private AnnoResultDao annoResultDao;

    @Autowired
    private AnnoLesionResultDao alrDao;

    @Autowired
    private AnnoComponentResultDao acrDao;

    @Transactional
    @Override
    public RespResult<Integer> create(Integer arId, String type, String info) {
        AnnoResultEntity ar = annoResultDao.findById(arId);
        if (null == ar) {
            return RespResult.secByError(RespCodeEnum.NOT_EXIST.getCode(), "标注结果不存在");
        }
        AnnoLesionResultGroupEntity group = new AnnoLesionResultGroupEntity(null, ar.getTaskId(), arId, type, info, null);
        annoLesionResultGroupDao.insertSelective(group);
        return RespResult.ok(group.getId());
    }

    @Transactional
    @Override
    public RespResult update(Integer id, String info) {
        AnnoLesionResultGroupEntity group = annoLesionResultGroupDao.findById(id);
        if (null == group) {
            return RespResult.error(RespCodeEnum.NOT_EXIST);
        }
        AnnoLesionResultGroupEntity updateGroup = new AnnoLesionResultGroupEntity(id, null, null, null, info, null);
        annoLesionResultGroupDao.updateByIdSelective(updateGroup);
        return RespResult.ok();
    }

    @Transactional
    @Override
    public RespResult delete(Integer id) {
        AnnoLesionResultGroupEntity group = annoLesionResultGroupDao.findById(id);
        if (null == group) {
            return RespResult.error(RespCodeEnum.NOT_EXIST);
        }

        annoLesionResultGroupDao.deleteById(id);

        List<Integer> alrIds = alrDao.findIdByArIdGroupId(group.getArId(), id);
        if (ArrayUtil.isEmpty(alrIds)) {
            return RespResult.ok();
        }

        alrDao.deleteByIds(alrIds.toArray());

        acrDao.deleteByAlrIds(alrIds);

        return RespResult.ok();
    }
}
